﻿namespace LMT.Communication.Tcp
{
    using System;
    using System.Net.Sockets;
    using System.IO;

    internal class TcpHelper
    {
        /// <summary>
        /// Gets the size of block buffer.
        /// </summary>
        internal int SizeOfBlockBuffer { get; private set;}

        /// <summary>
        /// 
        /// </summary>
        private static TcpHelper helperIns;

        /// <summary>
        /// Initializes a new instance of the <see cref="TcpHelper"/> class.
        /// </summary>
        private TcpHelper()
        {
            this.SizeOfBlockBuffer = 102400;
        }

        /// <summary>
        /// Creates the intance.
        /// </summary>
        /// <param name="bufferSize">Size of the buffer.</param>
        /// <returns></returns>
        internal static TcpHelper CreateIntance(int? bufferSize)
        {
            if (TcpHelper.helperIns == null)
            {
                TcpHelper.helperIns = new TcpHelper();
                if (bufferSize.HasValue)
                {
                    TcpHelper.helperIns.SizeOfBlockBuffer = bufferSize.Value;
                }
            }

            return TcpHelper.helperIns;
        }

        /// <summary>
        /// Gets or sets the instance.
        /// </summary>
        /// <value>
        /// The instance.
        /// </value>
        internal static TcpHelper Instance
        {
            get 
            {
                return TcpHelper.helperIns; 
            }
        }

        /// <summary>
        /// Sends the data.
        /// </summary>
        /// <param name="netStream">The net stream.</param>
        /// <param name="data">The data.</param>
        internal void SendData(Stream netStream, byte[] data)
        {
            ReadWriteData.SendBytes(netStream, data, this.SizeOfBlockBuffer);
        }

        /// <summary>
        /// Reads the data.
        /// </summary>
        /// <param name="netStream">The net stream.</param>
        internal byte[] ReadData(Stream netStream)
        {
            return ReadWriteData.ReadBytes(netStream, this.SizeOfBlockBuffer);
        }
    }
}